// 云函数入口文件
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const usersCollection = db.collection('users');
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const { nickName, avatarFileID } = event;

  if (!openid) {
    return {
      code: 500,
      msg: '获取用户OpenID失败'
    };
  }

  try {
    let userDataToUpdate = {};

    if (nickName && avatarFileID) {
      // 用户同意授权
      userDataToUpdate = {
        nickName: nickName,
        avatarUrl: avatarFileID, // 存储文件ID
        authorized: true,
        updateTime: new Date()
      };
      console.log(`用户 ${openid} 已授权，更新信息。`);
    } else {
      // 用户拒绝授权，生成默认信息
      const defaultNickName = `督搭用户_${openid.slice(-6)}`;
      // 注意：请预先将一个默认头像上传到云存储，并在此处填入其FileID
      const defaultAvatarUrl = 'cloud://prod-8g0wwd1b5fd10c45.7072-prod-8g0wwd1b5fd10c45-1257967285/default-avatar.png';
      
      userDataToUpdate = {
        nickName: defaultNickName,
        avatarUrl: defaultAvatarUrl,
        authorized: false,
        updateTime: new Date()
      };
      console.log(`用户 ${openid} 未授权，生成默认信息。`);
    }

    // 更新用户信息
    await usersCollection.where({
      _openid: openid
    }).update({
      data: userDataToUpdate
    });

    // 获取并返回更新后的完整用户信息
    const updatedUserResult = await usersCollection.where({
      _openid: openid
    }).get();

    if (updatedUserResult.data.length === 0) {
      throw new Error('更新后未能查询到用户信息');
    }

    return {
      code: 0,
      msg: '用户信息更新成功',
      data: {
        userInfo: updatedUserResult.data[0]
      }
    };

  } catch (error) {
    console.error(`更新用户信息失败 for openid: ${openid}`, error);
    return {
      code: 500,
      msg: '服务器内部错误',
      error: error.message
    };
  }
};